package com.web;

import com.bean.Account;
import com.dao.AccountDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/phone/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/account/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        if (username.length() == 0 || password.length() == 0 || code.length() == 0) {
            req.setAttribute("message", "输入有误！请重新输入");
            req.getRequestDispatcher("/account/result.jsp").forward(req, resp);
            return;
        }

        try {
            Account account = new AccountDao().login(username, password);
            if (account == null) {
                req.getSession().setAttribute("account", null);
                req.setAttribute("message", "用户名或密码错误！");
                req.getRequestDispatcher("/account/result.jsp").forward(req, resp);
            } else {
                HttpSession session = req.getSession();
                session.setAttribute("account", account);

                req.setAttribute("message", "登录成功");
                req.setAttribute("page", "/phone/list");
                req.getRequestDispatcher("/account/result.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            req.getSession().setAttribute("account", null);
            req.setAttribute("message", e.getLocalizedMessage());
            req.getRequestDispatcher("/account/result.jsp").forward(req, resp);
        }
    }
}

